package com.shiva.oms.biz;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shiva.oms.logview.domain.LogParseCfg;

/**
 * 
 * 将用户自定义的日志解析模板配置信息保存到本地文件
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2018年4月16日         LA.01367604           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author LA.01367604
 * @version 1.0
 */
public class CustomLogParseCfgBiz extends AbstractCustomTemp<LogParseCfg> {

    private static final Logger logger = LoggerFactory.getLogger(CustomLogParseCfgBiz.class);

    private static final String fileDir = "logv_conf";
    private static final String fileName = "custom_log_pattern.temp";
    private static final String ENTITY_SPLIT = ";";
    private static final String ENTITY_ATTR_SPLIT = ",";
    private File file = new File(CURRENT_DIR + FILE_SEP + fileDir + FILE_SEP + fileName);
    private List<LogParseCfg> cfgList;
    private static CustomLogParseCfgBiz instance;

    private CustomLogParseCfgBiz() {}

    public static CustomLogParseCfgBiz getInstance() {
        if (instance == null) {
            instance = new CustomLogParseCfgBiz();
        }
        return instance;
    }

    public List<LogParseCfg> getList() {
        if (cfgList == null) {
            cfgList = super.init(fileDir, fileName, file);
        }
        return cfgList;
    }

    public void addPattern(LogParseCfg rec) {
        if (cfgList == null) {
            cfgList = super.init(fileDir, fileName, file);
        }

        super.saveAll(cfgList, file);
    }

    public void removePattern(String id) {
        super.remove2List(cfgList, id);
    }

    public void updatePattern(LogParseCfg newCfg) {
        super.update(cfgList, newCfg.getId(), newCfg);
    }

    public List<LogParseCfg> reloadList() {
        cfgList = super.init(fileDir, fileName, file);
        return cfgList;
    }

    @Override
    protected String transList2Str(List<LogParseCfg> list) {
        return list.stream().map(LogParseCfg::toString).collect(Collectors.joining(ENTITY_SPLIT));
    }

    @Override
    protected List<LogParseCfg> transStr2List(String str) {
        List<LogParseCfg> list = new ArrayList<>();
        if (StringUtils.isNotBlank(str)) {
            String[] datas = str.split(ENTITY_SPLIT);
            for (int i = 0; i < datas.length; i++) {
                String[] temp = datas[i].split(ENTITY_ATTR_SPLIT);
                if (temp.length != 5) {
                    return list;
                }
                list.add(new LogParseCfg(temp[0], temp[1], temp[2], temp[3], temp[4]));
            }
        }
        return list;
    }

}
